package com.clei.Y2023.M10.D13.mqtt;

import com.clei.Y2023.M10.D13.com.MqttMessageCallback;
import com.clei.utils.PrintUtil;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * mqtt client
 * 发布消息
 *
 * @author Y
 * @date 2023-10-23
 */
public class MqttPublisher {

    /**
     * topic 消防
     */
    private static final String TOPIC = "topic/fire-control";

    /**
     * qos
     */
    private static final int QOS = 0;

    /**
     * broker
     */
    private static final String BROKER = "tcp://192.168.20.11:1883";

    /**
     * clientId
     */
    private static final String CLIENT_ID = "windows_ue";

    /**
     * username
     */
    private static final String USERNAME = "admin";

    /**
     * password
     */
    private static final String PASSWORD = "admin123";


    /**
     * MqttClient
     */
    private static MqttClient mqttClient = null;

    static {
        connect();
    }


    /**
     * 发送消息
     *
     * @param msg msg
     */
    public static void publish(String msg) {
        if (null == mqttClient) {
            return;
        }
        try {
            MqttMessage message = new MqttMessage(msg.getBytes());
            message.setQos(QOS);
            mqttClient.publish(TOPIC, message);
        } catch (Exception e) {
            PrintUtil.log("Message send error ", e);
        }
    }

    /**
     * 建立链接
     */
    public static void connect() {
        try {
            MqttClient client = new MqttClient(BROKER, CLIENT_ID, new MemoryPersistence());
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(USERNAME);
            connOpts.setPassword(PASSWORD.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);
            // 连接超时 10秒
            connOpts.setConnectionTimeout(10);

            // 设置回调
            client.setCallback(new MqttMessageCallback());

            // 建立连接
            PrintUtil.log("Connecting to broker : {}", BROKER);
            client.connect(connOpts);
            PrintUtil.log("Connected");

            mqttClient = client;
        } catch (Exception e) {
            PrintUtil.log("Connect error ", e);
        }
    }
}
